<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">

<div th:replace="~{component/head::head}"></div>

<body>

<div th:replace="~{component/header::header}"></div>

<div class="container-fluid">
  <div class="row">

    <div th:replace="~{component/nav::nav}"></div>

    <main id="app" class="col-md-9 ms-sm-auto col-lg-10 px-md-4 p-4">

      <h3>订单信息</h3>
      <hr>
      <p>
        <b>订单描述</b>：{{orderInfo.desc}}，
        <b>结算金额</b>：<span class="text-danger">{{orderInfo.amount}}</span> 元
      </p>
      <br>
      <h3>商品信息</h3>
      <hr>
      <p>
        <b>商品</b>：{{orderInfo.snapshot.productName}}，
        <b>单价</b>：{{orderInfo.snapshot.productPrice}} 元，
        <b>数量</b>：{{orderInfo.snapshot.productCount}}
      </p>
      <br>
      <div class="form-check" v-show="orderInfo.desc.indexOf('充值') === -1">
        <input v-model="isAccountPay" class="form-check-input" type="checkbox" id="flexCheckDefault">
        <label class="form-check-label" for="flexCheckDefault">
          余额支付，我的余额：{{account.amount}} 元，冻结：{{account.freezeAmount}} 元，可用余额：{{(account.amount - account.freezeAmount).toFixed(2)}}
        </label>
      </div>
      <br>
      <div v-for="c in ORDER_PAY_CHANNEL_ARRAY" :key="c.key" class="form-check form-check-inline">
        <input v-model="channel" class="form-check-input" type="radio" name="channelRadio" :id="c.key + '-radio'" :value="c.key">
        <label class="form-check-label" :for="c.key + '-radio'">{{c.value}}</label>
      </div>
      <br>
      <br>
      <p>
        <button @click="pay" class="btn btn-lg btn-primary" type="button">结 算</button>
      </p>

      <div class="modal fade" id="wxPayModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">请使用微信扫码支付</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <div id="qrcode"></div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
              <button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="window.location.href='order'">支付完成</button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<script>
  // 下面这行声明在一个页面只能有一次，header里已经有了，所以这里去掉
  // const {createApp, ref} = Vue;
  const app = createApp({
    setup() {
      const ORDER_PAY_CHANNEL_ARRAY = ref(window.ORDER_PAY_CHANNEL_ARRAY);
      const channel = ref();
      channel.value = window.ORDER_PAY_CHANNEL.ALIPAY.key;
      const orderInfo = ref();
      orderInfo.value = SessionStorage.get("ORDER");
      const account = ref();
      account.value = {};
      const isAccountPay = ref();

      const pay = () => {
        // 订单金额
        let amount = orderInfo.value.amount;
        // 会员可用余额
        let memberAmount = account.value.amount - account.value.freezeAmount;
        // 渠道支付金额
        let channelAmount = 0;
        // 余额支付金额
        let accountAmount = 0;
        if (isAccountPay.value) {
          if (memberAmount >= amount) {
            // 全部余额支付
            channelAmount = 0;
            accountAmount = amount;
          } else {
            // 部分余额支付
            channelAmount = amount - memberAmount;
            accountAmount = memberAmount;
          }
        } else {
          // 不用余额支付
          channelAmount = amount;
          accountAmount = 0;
        }
        channelAmount = channelAmount.toFixed(2);
        accountAmount = accountAmount.toFixed(2);

        Swal.fire({
          title: "支付确认",
          text: '本次将使用余额支付：' + accountAmount + '元，使用渠道支付：' + channelAmount + '元',
          confirmButtonText: '确认支付',
          showCancelButton: true
        }).then((result) => {
          // 如果不是点击【确认支付】，则不处理
          if (!result.value) {
            return;
          }
          axios.post("/pay/order-pay/pay", {
            "orderNo": orderInfo.value.orderNo,
            "channel": channel.value,
            "channelAmount": channelAmount,
            "accountAmount": accountAmount
          }).then((response) => {
            const data = response.data;
            if (data.success) {
              if (!data.content) {
                Msg.error("支付失败，请联系管理员！");
              } else {
                if (data.content === "1") {
                  // 纯余额支付成功
                  // 弹出支付确认框
                  Swal.fire({
                    title: "支付完成确认",
                    text: '您已完成支付，您的剩余可用余额：' + Math.abs(memberAmount - accountAmount).toFixed(2),
                    confirmButtonText: '确认',
                  }).then((result) => {
                    window.location.href="order";
                  })
                } else if (channel.value === window.ORDER_PAY_CHANNEL.ALIPAY.key) {
                  let payForm = document.getElementsByTagName('pay-form');
                  if (payForm.length) {
                    document.body.removeChild(payForm[0])
                  }
                  const div = document.createElement('pay-form');
                  div.innerHTML = data.content; // 支付宝返回的form
                  document.body.appendChild(div);
                  document.forms[0].setAttribute('target', '_blank');
                  document.forms[0].submit();

                  // 弹出支付完成确认框
                  Swal.fire({
                    title: "支付完成确认",
                    text: '支付完成后，点击【已完成支付】按钮',
                    confirmButtonText: '已完成支付',
                  }).then((result) => {
                    window.location.href = "order";
                  })
                } else if (channel.value === window.ORDER_PAY_CHANNEL.WXPAY.key) {
                  // 显示微信支付模态框
                  let wxPayModal = new bootstrap.Modal(document.getElementById('wxPayModal'), {
                    keyboard: false
                  });
                  wxPayModal.show();

                  // 生成二维码
                  document.getElementById('qrcode').innerHTML = "";
                  let qrcode = new QRCode('qrcode', {
                    text: data.content,
                    width: 200,
                    height: 200,
                    colorDark : '#000000',
                    colorLight : '#ffffff',
                    correctLevel : QRCode.CorrectLevel.H
                  });
                }
              }
            } else {
              Msg.error(data.message);
            }
          })
        });
      };

      const queryAccount = function () {
        axios.get("/system/account/query-one").then((response) => {
          const data = response.data;
          if (data.success) {
            account.value = data.content;
          } else {
            Msg.error(data.message);
          }
        });
      };

      onMounted(() => {
        queryAccount();
      });

      return {
        ORDER_PAY_CHANNEL_ARRAY,
        channel,
        orderInfo,
        pay,
        account,
        isAccountPay
      }
    }
  });
  app.mount("#app");
</script>

</body>
</html>
